const Doodoo = require("doodoo.js");
const socket = require("socket.io");
const Raven = require("raven");
const cors = require("koa-cors");
const context = require("./context");
const wxaXml = require("./middleware/wxa_xml");
const httpProxy = require("http-proxy");
const { URL } = require("url");
const path = require("path");
const _ = require("lodash");

const hProxy = httpProxy.createProxyServer({});
hProxy.on("error", (err, req, res) => {
    console.error(err);
    if (req.headers.upgrade && req.headers.upgrade === "websocket") {
        return;
    }
    res.writeHead(500, {
        "Content-Type": "application/json; charset=utf-8"
    });
    res.end(
        `{ "errmsg": "${err.name + " : " + err.message}", "errcode": "1" }`
    );
});

// 初始化
const app = new Doodoo();
Object.assign(app.context, context);

if (process.env.NODE_ENV === "docker") {
    Raven.config(
        "http://f9fdd721b4c44797ba703ece39c96904@sentry.oneqing.com/2",
        {
            release: "20180808"
        }
    ).install();
    app.on("error", err => {
        console.error(err);
        Raven.captureException(err, (err, eventId) => {
            console.log("Reported error " + eventId);
        });
    });
}

app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        console.error(err);
        Raven.captureException(err, (err, eventId) => {
            console.log("Reported error " + eventId);
        });
        ctx.fail(err.name + " : " + err.message);
    }
});
app.use(
    cors({
        credentials: true
    })
);
app.use(async (ctx, next) => {
    let proxyDomain;
    if (ctx.query.ProxyDomain) {
        proxyDomain = ctx.query.ProxyDomain;
        ctx.cookies.set("ProxyDomain", proxyDomain);
    } else {
        if (ctx.cookies.get("ProxyDomain")) {
            proxyDomain = ctx.cookies.get("ProxyDomain");
        }
    }
    if (proxyDomain) {
        const myURL = new URL(proxyDomain);
        const staticExts = [
            ".png",
            ".jpg",
            ".jpeg",
            ".bmp",
            ".gif",
            ".css",
            ".js"
        ];
        if (_.includes(staticExts, path.extname(ctx.path))) {
            ctx.redirect(`${myURL.protocol}//${myURL.host}${ctx.path}`);
            return;
        }

        ctx.respond = false;
        return hProxy.web(ctx.req, ctx.res, {
            target: `${myURL.protocol}//${myURL.host}${ctx.path}`,
            changeOrigin: true,
            ignorePath: true,
            headers: {
                Host: myURL.host,
                Cookie: ctx.get("Cookie"),
                Referer: ctx
                    .get("Referer")
                    .replace("api.doodooke.qingful.com", myURL.host)
            }
        });
    }
    await next();
});
app.use(wxaXml());
app.plugin("proxy");
app.plugin("baas");
app.plugin("gogs", {
    secret: "qingful",
    cmd: {
        start: "pm2 start pm2.json",
        restart: "pm2 restart pm2.json",
        stop: "pm2 stop pm2.json",
        pull: "git pull",
        install: "yarn install"
    }
});
app.plugin("dingding", {
    url:
        "xxx"
});

(async () => {
    const server = await app.start();
    doodoo.hook.run("dingding", "系统提示", "应用启动成功");

    // 全局
    global.io = socket(server);
    io.on("connection", async socket => {
        const sid = socket.id;
        const { uid } = socket.request._query;
        if (!uid) {
            return;
        }

        await doodoo.redis.setAsync(
            `wxLogin:uid:${uid}:sid`,
            sid,
            "EX",
            60 * 60 * 2
        );
    });
})();
